from django import template
from django.utils.html import format_html
from xadmin.models import Node
from xadmin.plugins.permission import CheckPerm

register = template.Library()


@register.filter
def digui(children_list):
    html = ""
    if children_list:
        inner = '<ol class="dd-list">'
        for c in children_list:
            inner += '''
                    <li class="dd-item" data-id="2">
                        <div class="dd-handle">
                            <span class="pull-right"> 
                                <i class="fa fa-arrow-up moveup" title="上移" id="%s"></i>
                                <i class="fa fa-arrow-down movedown" title="下移" id="%s"></i>
                                <i class="fa fa-pencil-square-o edit" title="编辑" id='%s'></i>
                                <i class="fa fa-trash del" title="删除" id='%s'></i>
                            </span>
                            <span class="label label-info"><i class="fa fa-folder"></i></span> 
            ''' % (c.id, c.id, c.id, c.id)
            inner += c.name
            inner += '</div>'
            inner += digui(c.children)
            inner += '</li>'

        inner += '</ol>'
        html += inner
        #print(html)
    return format_html(html)


@register.filter
def info_or_warning(loop):
    if loop % 2 == 0:
        return 'label-warning'
    else:
        return 'label-info'


@register.simple_tag
def isActive(mbx, string):
    if string in mbx:
        return 'active'
    else:
        return ''


@register.filter
def status(user_active):
    if user_active:
        return '正常'
    else:
        return '已锁定'

@register.filter
def userType(is_staff):
    if is_staff:
        return '管理员'
    else:
        return '前台用户'


@register.filter
def grouplist(user):
    groups = []
    for u in user.user_group.all():
        groups.append(u.name)
    return ','.join(groups) if groups else ' '


@register.filter
def isChecked(user, groupid):
    for g in  user.user_group.all():
        if g.id == groupid:
            return 'checked'
    else:
        return ''


@register.simple_tag
def article_group_is_checked(gid, group_queryset):
    for g in group_queryset:
        if g.id == gid:
            return "checked"
    return ''

@register.filter
def goright(node_level):
    return '|' + ('--'*node_level)

@register.filter
def isDisabled(node_type):
    if node_type == '' or node_type is None:
        return 'disabled=""'

@register.filter
def tow_number(num):
    num = str(num)
    if len(num) < 2:
        return '0' + num
    return num[-2:]


def check_prem(perm_dic, perm_type, perm_slug):
    for p_type, p_list in perm_dic.items():
        if perm_type == p_type:
            if perm_slug in p_list:
                return True




